package com.tqfframe.studydemo.myDubboRpc.core;

import com.tqfframe.studydemo.myDubboRpc.core.handler.ClinetHandler;
import com.tqfframe.studydemo.myDubboRpc.core.porxy.ClinetPorxy;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by Tang-QiFeng on 2022/2/18
 */
public class RpcClinet implements Clinet {

    private Logger logger=LoggerFactory.getLogger(this.getClass());

    final static String RPC_SERVER_HOST = "DUBBO_RPC_SERVER_HOST";
    final static String RPC_SERVER_PORT = "DUBBO_RPC_SERVER_PORT";

    private static ClinetHandler client;


    @Override
    public Object getServer(Class aClass) throws IOException {
        //读取配置文件
        Properties properties = new Properties();
        InputStream resourceAsStream = aClass.getClassLoader().getResourceAsStream("rpc/RpcConfig.properties");
        properties.load(resourceAsStream);
        String host = properties.getProperty(RPC_SERVER_HOST);
        Integer port = new Integer((String) properties.get(RPC_SERVER_PORT));
        if(client==null){
            initClinetHandler(host,port);
        }
        //使用动态代理去调用方法,方法增强是通过netty去服务端拿方法的实现数据
        return new ClinetPorxy(aClass ,client).creatProxyedObj();
    }

    /**
     * 初始化客户端handler
     * @param host
     * @param port
     */
    private  void initClinetHandler( String host  ,Integer port){
        client = new ClinetHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new StringDecoder());
                        p.addLast(new StringEncoder());
                        //重要！！！这里定义了客户端处理类。
                        p.addLast(client);
                    }
                });
        try {
            b.connect(host, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("netty clinet ...."+host+":"+port);
    }
}
